<template>
  <div class="lhx-doctor-chat-container">
    <div class="lhx-header">
      <h2>医生聊天列表界面</h2>
      <p class="lhx-user-info">当前用户: {{ lhxCurrentUser.name }} ({{ lhxCurrentUser.userId }})</p>
      <!-- Socket连接状态 -->
      <div v-if="lhxPatients.length > 0" class="lhx-connection-status">
        <span v-if="lhxConnecting" class="lhx-status-connecting">🔄 正在连接实时通讯...</span>
        <span v-else-if="lhxSocketConnected" class="lhx-status-connected">🟢 实时通讯已连接</span>
        <span v-else class="lhx-status-disconnected">🔴 实时通讯未连接</span>
      </div>
    </div>
    
    <!-- 加载状态 -->
    <div v-if="lhxLoading" class="lhx-loading">
      <p>正在加载患者聊天列表...</p>
    </div>
    
    <!-- 错误提示 -->
    <div v-if="lhxError" class="lhx-error">
      <p>{{ lhxError }}</p>
      <button @click="lhxLoadPatients" class="lhx-retry-btn">重新加载</button>
    </div>
    
    <!-- 患者聊天列表 -->
    <div v-if="!lhxLoading && !lhxError" class="lhx-patient-list">
      <div v-if="lhxPatients.length === 0" class="lhx-empty">
        <p>暂无患者聊天</p>
        <small>等待患者主动发起聊天</small>
      </div>
      
      <div 
        v-for="chat in lhxPatients" 
        :key="chat.roomId"
        class="lhx-patient-item"
        @click="lhxOpenChat(chat)"
      >
        <div class="lhx-patient-avatar">
          <img :src="chat.patient.avatar || '/default-patient.png'" :alt="chat.patient.name" />
        </div>
        <div class="lhx-patient-info">
          <div class="lhx-patient-header">
            <span class="lhx-patient-name">{{ chat.patient.name }}</span>
            <span class="lhx-message-time">{{ lhxFormatTime(chat.lastMessage.timestamp) }}</span>
          </div>
          <div class="lhx-last-message">
            <span class="lhx-sender-label">
              {{ chat.lastMessage.senderType === 'doctor' ? '我' : chat.patient.name }}:
            </span>
            {{ chat.lastMessage.content }}
          </div>
          <div class="lhx-chat-stats">
            <span class="lhx-message-count">{{ chat.messageCount }}条消息</span>
            <span v-if="chat.unreadCount > 0" class="lhx-unread-badge">
              {{ chat.unreadCount }}
            </span>
          </div>
        </div>
        <div class="lhx-chat-arrow">
          <span>💬</span>
        </div>
      </div>
    </div>
    
    <!-- 底部导航栏，组长的模块，不用写 -->
    <div class="lhx-footer">
      <p>底部导航栏，组长的模块，不用写</p>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue';
import { useRouter } from 'vue-router';
import { io, Socket } from 'socket.io-client';

const router = useRouter();

// 响应式数据
const lhxLoading = ref(false);
const lhxError = ref('');
const lhxPatients = ref<any[]>([]);

// Socket相关状态
const lhxSocket = ref<Socket | null>(null);
const lhxSocketConnected = ref(false);
const lhxConnecting = ref(false);

// 当前用户信息（从localStorage获取，兼容演示页面）
const lhxCurrentUser = ref((() => {
  try {
    const stored = localStorage.getItem('lhx_current_user');
    if (stored) {
      return JSON.parse(stored);
    }
  } catch (error) {
    console.warn('LHX: 获取用户信息失败', error);
  }
  
  // 默认医生信息
  return {
    userId: 'd001',
    name: '张医生',
    userType: 'doctor'
  };
})());

/**
 * 格式化时间显示
 */
function lhxFormatTime(timestamp: string) {
  if (!timestamp) return '';
  
  const date = new Date(timestamp);
  const now = new Date();
  const diffTime = now.getTime() - date.getTime();
  const diffMinutes = Math.floor(diffTime / (1000 * 60));
  const diffHours = Math.floor(diffTime / (1000 * 60 * 60));
  const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24));
  
  if (diffMinutes < 1) return '刚刚';
  if (diffMinutes < 60) return `${diffMinutes}分钟前`;
  if (diffHours < 24) return `${diffHours}小时前`;
  if (diffDays < 7) return `${diffDays}天前`;
  
  return date.toLocaleDateString();
}

/**
 * 加载患者聊天列表
 */
async function lhxLoadPatients() {
  lhxLoading.value = true;
  lhxError.value = '';
  
  try {
    const response = await fetch(`http://localhost:3000/lhx/doctor/${lhxCurrentUser.value.userId}/patients`);
    const result = await response.json();
    
    if (result.success) {
      lhxPatients.value = result.data;
      console.log('LHX: 加载患者聊天列表成功', result.data);
      
      // 加载完列表后，建立Socket连接监听实时更新
      if (!lhxSocket.value && lhxPatients.value.length > 0) {
        lhxConnectSocket();
      } else if (lhxSocket.value && lhxSocketConnected.value) {
        // 如果Socket已连接，更新监听的房间
        lhxMonitorChatRooms();
      }
    } else {
      lhxError.value = result.message || '获取患者聊天列表失败';
    }
  } catch (error) {
    console.error('LHX: 加载患者聊天列表失败', error);
    lhxError.value = '网络连接失败，请检查网络或后端服务';
  } finally {
    lhxLoading.value = false;
  }
}

/**
 * 建立Socket连接
 */
function lhxConnectSocket() {
  if (lhxSocket.value) return;
  
  lhxConnecting.value = true;
  console.log('LHX-List: 连接Socket到 http://localhost:3000');
  
  lhxSocket.value = io('http://localhost:3000', {
    transports: ['websocket', 'polling']
  });
  
  // 连接成功
  lhxSocket.value.on('connect', () => {
    console.log('LHX-List: Socket连接成功');
    lhxSocketConnected.value = true;
    lhxConnecting.value = false;
    lhxMonitorChatRooms();
  });
  
  // 连接失败
  lhxSocket.value.on('connect_error', (error) => {
    console.error('LHX-List: Socket连接失败', error);
    lhxSocketConnected.value = false;
    lhxConnecting.value = false;
  });
  
  // 断开连接
  lhxSocket.value.on('disconnect', () => {
    console.log('LHX-List: Socket连接断开');
    lhxSocketConnected.value = false;
  });
  
  // 监听新消息
  lhxSocket.value.on('lhx_receive_message', (message) => {
    console.log('LHX-List: 收到新消息', message);
    lhxHandleNewMessage(message);
  });
  
  // 监听房间监听确认
  lhxSocket.value.on('lhx_room_monitored', (data) => {
    console.log('LHX-List: 房间监听确认', data);
  });
  
  // 错误处理
  lhxSocket.value.on('lhx_error', (error) => {
    console.error('LHX-List: Socket错误', error);
  });
}

/**
 * 监听所有相关聊天房间
 */
function lhxMonitorChatRooms() {
  if (!lhxSocket.value || lhxPatients.value.length === 0) return;
  
  console.log('LHX-List: 开始监听聊天房间');
  
  // 对每个聊天房间，模拟加入以监听消息（不发送历史消息）
  lhxPatients.value.forEach(chat => {
    const [patientId, doctorId] = chat.roomId.split('_');
    
    // 发送特殊的监听请求，仅用于列表页面监听
    lhxSocket.value?.emit('lhx_monitor_room', {
      patientId,
      doctorId,
      userType: lhxCurrentUser.value.userType,
      userId: lhxCurrentUser.value.userId,
      isListPage: true  // 标识这是列表页面的监听
    });
  });
}

/**
 * 处理新收到的消息，更新列表
 */
function lhxHandleNewMessage(message: any) {
  const chatIndex = lhxPatients.value.findIndex(chat => chat.roomId === message.roomId);
  
  if (chatIndex !== -1) {
    // 更新现有聊天的最新消息
    const chat = lhxPatients.value[chatIndex];
    chat.lastMessage = {
      content: message.content,
      senderId: message.senderId,
      senderType: message.senderType,
      timestamp: message.timestamp,
      messageType: message.messageType
    };
    
    // 如果消息不是医生发送的，增加未读计数
    if (message.senderType !== 'doctor') {
      chat.unreadCount = (chat.unreadCount || 0) + 1;
    }
    
    // 将此聊天移到列表顶部
    const updatedChat = lhxPatients.value.splice(chatIndex, 1)[0];
    lhxPatients.value.unshift(updatedChat);
    
    console.log('LHX-List: 列表已更新', { roomId: message.roomId, unreadCount: chat.unreadCount });
  } else {
    // 如果是新的聊天，重新加载列表
    console.log('LHX-List: 发现新聊天，重新加载列表');
    lhxLoadPatients();
  }
}

/**
 * 断开Socket连接
 */
function lhxDisconnectSocket() {
  if (lhxSocket.value) {
    console.log('LHX-List: 断开Socket连接');
    lhxSocket.value.disconnect();
    lhxSocket.value = null;
  }
  lhxSocketConnected.value = false;
}

/**
 * 打开与患者的聊天
 */
function lhxOpenChat(chat: any) {
  console.log('LHX: 打开聊天', {
    patient: chat.patient.name,
    roomId: chat.roomId
  });
  
  // 清零未读计数（本地更新，实际标记已读在聊天窗口处理）
  chat.unreadCount = 0;
  
  router.push({
    path: '/lhx-chat',
    query: {
      lhxRoomId: chat.roomId,
      lhxPatientId: chat.patient.userId,
      lhxPatientName: chat.patient.name,
      lhxUserId: lhxCurrentUser.value.userId,
      lhxUserType: lhxCurrentUser.value.userType,
      lhxUserName: lhxCurrentUser.value.name
    }
  });
}

// 组件挂载时加载数据
onMounted(() => {
  console.log('LHX-List: 组件挂载，开始加载数据');
  lhxLoadPatients();
});

// 组件卸载时清理资源
onUnmounted(() => {
  console.log('LHX-List: 组件卸载，清理Socket连接');
  lhxDisconnectSocket();
});
</script>

<style scoped>
.lhx-doctor-chat-container {
  max-width: 600px;
  margin: 0 auto;
  padding: 20px;
  background: #f8f9fa;
  min-height: 100vh;
}

.lhx-header {
  text-align: center;
  margin-bottom: 20px;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.lhx-header h2 {
  color: #2c3e50;
  margin-bottom: 10px;
}

.lhx-user-info {
  color: #666;
  font-size: 14px;
  margin: 0;
}

.lhx-connection-status {
  margin-top: 8px;
  font-size: 12px;
}

.lhx-status-connecting {
  color: #f39c12;
}

.lhx-status-connected {
  color: #27ae60;
}

.lhx-status-disconnected {
  color: #e74c3c;
}

.lhx-loading {
  text-align: center;
  padding: 40px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.lhx-error {
  text-align: center;
  padding: 40px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  border-left: 4px solid #e74c3c;
}

.lhx-error p {
  color: #e74c3c;
  margin-bottom: 15px;
}

.lhx-retry-btn {
  background: #3498db;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
}

.lhx-retry-btn:hover {
  background: #2980b9;
}

.lhx-patient-list {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  overflow: hidden;
  margin-bottom: 20px;
}

.lhx-empty {
  text-align: center;
  padding: 40px;
  color: #666;
}

.lhx-empty small {
  display: block;
  margin-top: 8px;
  color: #999;
}

.lhx-patient-item {
  display: flex;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #eee;
  cursor: pointer;
  transition: background-color 0.2s;
}

.lhx-patient-item:hover {
  background-color: #f8f9fa;
}

.lhx-patient-item:last-child {
  border-bottom: none;
}

.lhx-patient-avatar {
  width: 50px;
  height: 50px;
  margin-right: 12px;
}

.lhx-patient-avatar img {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  object-fit: cover;
  background: #e0e0e0;
}

.lhx-patient-info {
  flex: 1;
}

.lhx-patient-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 6px;
}

.lhx-patient-name {
  font-size: 16px;
  font-weight: bold;
  color: #2c3e50;
}

.lhx-message-time {
  font-size: 12px;
  color: #999;
}

.lhx-last-message {
  font-size: 14px;
  color: #666;
  margin-bottom: 6px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.lhx-sender-label {
  color: #3498db;
  font-weight: bold;
}

.lhx-chat-stats {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.lhx-message-count {
  font-size: 12px;
  color: #999;
}

.lhx-unread-badge {
  background: #e74c3c;
  color: white;
  font-size: 12px;
  padding: 2px 6px;
  border-radius: 10px;
  min-width: 18px;
  text-align: center;
}

.lhx-chat-arrow {
  font-size: 20px;
  color: #3498db;
}

.lhx-footer {
  text-align: center;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  color: #666;
  font-style: italic;
}
</style>